package com.jdd.modules.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jdd.common.api.vo.Result;
import com.jdd.common.util.ResultGenerator;
import com.jdd.dao.entity.TProject;
import com.jdd.dao.service.TProjectService;
import com.jdd.modules.project.entity.SysProject;
import com.jdd.modules.project.service.SysProjectService;
import com.jdd.modules.project.vo.ProjectAddVO;
import com.jdd.modules.system.entity.SysUser;
import com.jdd.modules.system.service.ISysUserService;
import com.jdd.modules.userstaff.entity.User;
import com.jdd.modules.userstaff.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 *
 * @author : liuyaowen
 * @describe: 人行项目管理
 * @date: 2022-09-27
 */
@Slf4j
@RestController()
@RequestMapping("/sysProject")
public class SysProjectController {

    @Resource
    private SysProjectService sysProjectService;
    @Resource
    private ISysUserService sysUserService;



    @Resource
    private TProjectService tProjectService;

    @Resource
    private IUserService userService;



    @GetMapping("/page")
    public Result<IPage<SysProject>> page(SysProject sysProject, @RequestParam("pageSize")Integer pageSize, @RequestParam("pageNo")Integer pageNo){
        Page<SysProject> page = new Page<>(pageNo,pageSize);
        Result<IPage<SysProject>> pageResult = new Result<>();
        IPage<SysProject> ipage = sysProjectService.page(page, sysProject);
        for (SysProject record : ipage.getRecords()) {
            QueryWrapper<TProject> queryWrapper =  new QueryWrapper<>();
            queryWrapper.eq("sys_project_code",record.getProjectCode());
            QueryWrapper<SysUser> queryWrapper1 =  new QueryWrapper<>();
            queryWrapper1.eq("org_code",record.getProjectCode());
            QueryWrapper<User> queryWrapper2 =  new QueryWrapper<>();
            queryWrapper2.eq("sys_project_code",record.getProjectCode());
            record.setProjectNumber(tProjectService.count(queryWrapper));
            record.setSysUserNumber(sysUserService.count(queryWrapper1));
            record.setProjectUserNumber(userService.count(queryWrapper2));
        }
        pageResult.setResult(ipage);
        return pageResult.success("查询完成");
    }
    @GetMapping("/list")
    public Result<List<SysProject>> list(){
        Result<List<SysProject>> pageResult = new Result<>();
        pageResult.setResult( sysProjectService.list());
        return pageResult.success("查询完成");
    }
    @DeleteMapping("/delete")
    public Result delete(@RequestParam(name = "id")String id){
        /*判断下当前人行项目下是否还存在用户*/
        SysProject sys = sysProjectService.getById(id);
        String projectCode = sys.getProjectCode();
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_code",projectCode);
        List<SysUser> list = sysUserService.list(queryWrapper);
        if (list!=null && list.size()>0){
            return ResultGenerator.genFailResult("该项目下存在用户，请删除用户后执行该操作");
        }
        /*删除操作会删除此人行项目下的所有数据*/
        deleteData(id);
        sysProjectService.removeById(id);
        return ResultGenerator.genSuccessResult("删除成功");
    }

    private void deleteData(String id) {
        sysProjectService.deleteData(id);
    }

    @DeleteMapping("batchDel")
    public Result batchDel(@RequestParam(name = "ids")String ids){
        List<Serializable> idList = Lists.newArrayList(ids.split(","));
        for (Serializable id : idList) {
            /*逐个判断人行项目下是否存在用户*/
            SysProject sys = sysProjectService.getById(id);
            String projectCode = sys.getProjectCode();
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("org_code",projectCode);
            List<SysUser> list = sysUserService.list(queryWrapper);
            if (list!=null && list.size()>0){
                return ResultGenerator.genFailResult(sys.getProjectName()+ "该项目下存在用户，请删除用户后执行该操作");
            }
        }
        sysProjectService.removeByIds(idList);
        return ResultGenerator.genSuccessResult("批量删除完成");
    }

    @PostMapping("/add")
    public Result<String> add(@RequestBody ProjectAddVO projectAddVO){
        Result<String> result = new Result<>();
        try {
            sysProjectService.addProject(projectAddVO);
        }catch (Exception e)
        {
            log.error("{}",e);
            if(e.getClass().equals(DuplicateKeyException.class))
            {
                Pattern p = Pattern.compile("'(.*?)'");
                String str = e.getCause().getMessage();
                Matcher m=p.matcher(str);
                if(m.find()){
                    result.setMessage("数据重复=>"+m.group().replace("'", ""));
                }
            }
            result.setSuccess(false);
        }
        return result;
    }

}
